package bio_nio_aio.bio.com_base.netcode;

import org.junit.jupiter.api.Test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;


public class TestTcp3 {

	// 客户端
	@Test
	public void client() throws UnknownHostException, IOException {

		FileInputStream fs = new FileInputStream("C:\\Users\\admin\\Desktop\\test\\Test.txt");
		BufferedInputStream bfs = new BufferedInputStream(fs);
		
		Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
		OutputStream os = socket.getOutputStream();
		BufferedOutputStream bs = new BufferedOutputStream(os);
		
		byte[] b = new byte[20];
		int len;
		while ((len = bfs.read(b)) != -1) {
			bs.write(b, 0, len);
		}
		bs.flush();
		socket.shutdownOutput();
		// 读取返回的信息
		InputStream is = socket.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		
		while ((len = bis.read(b)) != -1) {
			System.out.println(new String(b, 0, len));
		}

		bis.close();
		socket.close();
		bfs.close();
		
	}

	// 服务端
	@Test
	public void server() throws IOException {

		ServerSocket ss = new ServerSocket(9090);
		Socket socket = ss.accept();
		InputStream is = socket.getInputStream();
		FileOutputStream fo = new FileOutputStream("C:\\Users\\admin\\Desktop\\Test.txt");
		byte[] b = new byte[20];
		int len;
		while ((len = is.read(b)) != -1) {
			fo.write(new String(b, 0, len).toUpperCase().getBytes(), 0, len);
		}
		// 收到来自哪里的文件
		System.out.println("收到来自 " + socket.getInetAddress().getHostAddress() + "的文件!");

		// 给客户端返回上传成功的数据
		OutputStream os = socket.getOutputStream();
		os.write("上传成功!".getBytes());
		os.flush();

		fo.close();
		is.close();
		socket.close();
		ss.close();
	}
}
